package com.epoch.platform.sys.user.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSON;
import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.model.BaseModel;
import com.epoch.base.util.AjaxResult;
import com.epoch.base.util.JSONUtils;
import com.epoch.base.util.LoggerUtil;
import com.epoch.base.util.MD5Utils;
import com.epoch.platform.sys.org.service.SysOrgService;
import com.epoch.platform.sys.user.dao.SysUser;
import com.epoch.platform.sys.user.service.SysUserService;
import com.epoch.platform.sys.userorg.dao.SysUserOrg;
import com.epoch.platform.sys.userrole.dao.SysUserRole;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
/**
 * 
* <p>Title: SysUserController</p>  
* <p>Description:用户管理 </p>  
* @author zhangqinglei
* @email 544188838@qq.com
* @date 2018年8月19日
 */
@ControllerBind(controllerKey = "/sys/user")
public class SysUserController extends BaseController {
	
	private static final Logger logger = LoggerUtil.getLogger();
	
	private AjaxResult ajaxResult = new AjaxResult();

	private SysOrgService sysOrgService = this.enhance(SysOrgService.class);

	private SysUserService service = this.enhance(SysUserService.class);

	public void index() {
		render("/sys/user/sys_user_tab.html");
	}
	
	public void listUI() {
		setAttr("treeNodeJson", JSON.toJSON(sysOrgService.getAllTreeOrgList()));
		render("/sys/user/sys_user_list.html");
	}

	public void findUserListAjax() {
		Kv param = commonParams();
		String parentId = null;
		if (getPara("parentId") != null) {
			parentId = getPara("parentId");
			if (getPara("parentId").equalsIgnoreCase("0")) {
				parentId = null;
			}
		}
		param.set("parent_id", parentId);
		SqlPara sqlPara = Db.getSqlPara("systemManage.findSysUserList", param);
		Page<SysUser> sysUserList = SysUser.dao.paginate(sqlPara, param);
		renderJson(sysUserList);
	}

	public void suvUI() {
		String id = getPara("ID");
		SysUser sysUser;
		if (StringUtils.isNotBlank(id)) {
			sysUser = SysUser.dao.findById(id);
			//用户_组织列表
            SysUserOrg userOrg = SysUserOrg.dao.findFirst(Db.getSql("systemManage.selectUserOrgByUserId"), sysUser.getStr("dept_id"));
            sysUser.put("DEPT_SHOW", userOrg != null ? userOrg.get("org_name") : "");
		} else {
			sysUser = new SysUser();
			sysUser.put("dept_id", getParaValuesToStr("parentId", "0"));
            sysUser.put("DEPT_SHOW", getPara("parentName", "组织结构树"));
            setAttr("title", "新增用户");// 用户
		}
		setAttr("treeNodeJson", JSONUtils.toJSONString(sysOrgService.getAllTreeOrgList()));
		setAttr("sysUser", sysUser);// 用户
		render("/sys/user/sys_user_edit.html");
	}
	
	public void findUserRole() {
		Page<? extends BaseModel<?>> page = null;
        String userId = this.getPara("userId");
        if (userId != null) {
            Kv params = this.commonParams();
            params.set("userId", userId);
            String roleType = this.getPara("roleType");
            params.set("roleType", roleType);
            List<SysUserRole> list = SysUserRole.dao.find(Db.getSqlPara("systemManage.selectUserRoleByUserIdAndRoleType", params));
            int cnt = list == null ? 0 : list.size();
            page = new Page<SysUserRole>(list, 0, cnt, 1, cnt);
        } else {
            page = new Page<BaseModel<?>>(new ArrayList<BaseModel<?>>(), 0, 0, 0, 0);
        }
        this.renderJson(page);
	}
	
	public void saveOrUpdate() {
        try {
            SysUser user = getModel(SysUser.class, "sysUser");
            if (user != null) {
                Map<String, List<SysUserRole>> userSysRolesMap = this.getTableEditParams(SysUserRole.class, "userSysRoles", null);
                //获取上传对象
                String uploaderData = getPara("uploader");
                user.put("uploaderData", uploaderData);
                this.service.saveSysUser(user, userSysRolesMap);
            }
            renderJson(ajaxResult.success("保存成功"));
        } catch (Exception e) {
        	logger.error("保存用户信息失败，", e);
        	renderJson(ajaxResult.addError("保存失败"));
        	if(e.getClass() == ActiveRecordException.class) {
        		throw new RuntimeException();
        	}
        }
    }
	
	/**
     * 校验用户名是否存在
     */
    public void verifyAccount() {
        String account = getPara("sysUser.ACCOUNT");
        String id = getPara("sysUser.ID");
        String msg = "";
        if (StringUtils.isNotBlank(account)) {
            SysUser user = SysUser.dao.findFirst("select t.id from sys_user t where t.account = ? ", account);
            if (user != null && !user.get("ID").toString().equals(id)) {
            	msg = "用户名已存在";
            }
        }
        this.renderText(msg);
    }
	
	/**
     * 校验用员工编号是否存在
     */
    public void verifyEmployeeNumber() {
        String employee_number = getPara("sysUser.EMPLOYEE_NUMBER");
        String id = getPara("sysUser.ID");
        String msg = "";
        if (StringUtils.isNotBlank(employee_number)) {
            SysUser user = SysUser.dao.findFirst("select t.id from sys_user t where t.employee_number = ? ", employee_number);
            if (user != null && !user.getStr("ID").equals(id)) {
            	msg = "员工编号已存在";
            }
        }
        this.renderText(msg);
    }
    
    /**
     * 删除
     */
    public void delete() {
        String[] ids = getParaValues("ids[]");
        try {
            this.service.deleteUserByIds(ids);
        } catch (Exception e) {
        	logger.error("删除失败", e);
        }
        redirect("/sys/user");
    }
    
    /**
     * 初始化密码
     */
    public void resetPassword() {
        String id = getPara("ID");
        String passWord = MD5Utils.getMd5("123456");
        String msg = "false";
        if (StringUtils.isNotBlank(id)) {
            Db.update("update sys_user set password = ? where id = ?", passWord, id);
            msg = "true";
        }
        renderText(msg);
    }
    
    /**
     * 修改密码密码
     */
    public void updatePassword() {
        String userId = getPara("userId");
        String passwordOld = getPara("passwordOld");
        String passwordNew = getPara("passwordNew");
        passwordOld = MD5Utils.getMd5(passwordOld);
        passwordNew = MD5Utils.getMd5(passwordNew);
        SysUser sysUser = SysUser.dao.findById(userId);
        String msg = "false";
        if (null != sysUser) {
            String passwordDb = sysUser.getStr(SysUser.PASSWORD);
            if (passwordDb.equals(passwordOld)) {
                Db.update("update sys_user set password = ? where id = ?", passwordNew, userId);
                msg = "true";
            }
        }
        renderText(msg);
    }
}
